package cn.wolfcode.shop.cloud.service.impl;



import cn.wolfcode.shop.cloud.common.BusinessException;
import cn.wolfcode.shop.cloud.mapper.SeckillOrderInfoMapper;
import cn.wolfcode.shop.cloud.msg.SeckillCodeMsg;
import cn.wolfcode.shop.cloud.service.ISeckillOrderInfoService;
import cn.wolfcode.shop.cloud.service.ISeckillGoodService;
import cn.wolfcode.shop.cloud.service.ISeckillOrderService;
import cn.wolfcode.shop.cloud.util.IdGenerateUtil;
import cn.wolfcode.shop.cloud.vo.SeckillGoodVo;
import domain.OrderInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 *
 */
@Service
public class SeckillOrderInfoServiceImpl implements ISeckillOrderInfoService {

    @Autowired
    private ISeckillGoodService seckillGoodService;
    @Autowired
    private ISeckillOrderService seckillOrderService;
    @Autowired
    private SeckillOrderInfoMapper seckillOrderInfoMapper;


    @Override
    @Transactional
    public String doSeckill(Long userId, Long seckillId) {
        //6 具体秒杀的业务
        //  6.1  减少库存 -1
        int count = seckillGoodService.decr(seckillId);
        if(count == 0){
            throw  new BusinessException(SeckillCodeMsg.SECKLILL_STOCKET_OVER);
        }


        //  6.2  创建订单信息然后把数据封装进去保存到数据库中
        String orderNo = createOrderInfo(userId,seckillId);


        //  6.3  创建秒杀订单信息,往t_seckill_order插入一条数据作为这个用户已经下单的依据
        seckillOrderService.createSeckillOrder(userId,seckillId,orderNo);
        return orderNo;
    }

    @Override
    public OrderInfo queryByOrderNo(String orderNo) {
        return seckillOrderInfoMapper.queryByOrderNo(orderNo);
    }

    @Override
    public int changOrderInfoStatus(String orderNo, Integer status) {
        return seckillOrderInfoMapper.changOrderInfoStatus(orderNo,status);
    }

    @Override
    public void changPayStatus(String orderNo, Integer status) {
       seckillOrderInfoMapper.changPayStatus(orderNo,status);
    }


    private String createOrderInfo(Long userId, Long seckillId) {
        SeckillGoodVo seckillGoodVO = seckillGoodService.queryById(seckillId);
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setCreateDate(new Date());
        orderInfo.setGoodCount(seckillGoodVO.getStockCount());
        orderInfo.setGoodId(seckillGoodVO.getGoodId());
        orderInfo.setGoodImg(seckillGoodVO.getGoodImg());
        orderInfo.setGoodName(seckillGoodVO.getGoodName());
        orderInfo.setGoodPrice(seckillGoodVO.getGoodPrice());
        orderInfo.setUserId(userId);
        orderInfo.setSeckillPrice(seckillGoodVO.getSeckillPrice());
        orderInfo.setOrderNo(IdGenerateUtil.get().nextId()+"");

        seckillOrderInfoMapper.save(orderInfo);

        return orderInfo.getOrderNo();
    }
}
